<template>
  <div class="role-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">角色管理</h1>
        <p class="page-description">探索和管理各种角色，从历史人物到虚构角色</p>
      </div>
      <div class="header-actions">
        <!-- <CloneButton @success="handleCloneSuccess" /> -->
        <a-button type="primary" size="large" class="create-btn" @click="handleCreateRole">
          <template #icon>
            <Plus :size="16" />
          </template>
          新建角色
        </a-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-filter-row">
        <div class="search-container">
          <a-input
            v-model:value="searchKeyword"
            placeholder="搜索角色名称、描述或特征..."
            size="small"
            class="search-input"
            @input="handleSearch($event.target.value)"
          >
            <template #prefix>
              <Search :size="16" />
            </template>
          </a-input>
        </div>
        
        <div class="filter-group">
          <span class="filter-label">分类筛选：</span>
          <a-select
            v-model:value="selectedCategory"
            placeholder="选择分类"
            style="width: 120px"
            @change="handleCategoryChange"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="default">默认</a-select-option>
            <a-select-option value="custom">自定义</a-select-option>
          </a-select>
        </div>
      </div>
    </div>

    <!-- 角色卡片列表 -->
    <div class="roles-grid">
      <div
        v-for="role in filteredRoles"
        :key="role.id"
        class="role-card"
        @click="handleRoleClick(role)"
      >
        <div class="role-avatar">
          <a-avatar 
            :size="60" 
            :src="role.avatarUrl || role.avatar"
            :shape="'square'"
            :style="{ 
              background: role.avatarUrl || role.avatar ? 'transparent' : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
              fontSize: '24px',
              fontWeight: '600',
              borderRadius: '8px'
            }"
          >
            {{ !role.avatarUrl && !role.avatar ? (role.roleName?.[0] || 'R') : '' }}
          </a-avatar>
        </div>
        
        <div class="role-info">
          <h3 class="role-name">{{ role.roleName }}</h3>
          <p class="role-description">{{ role.prompt }}</p>
          
          <div class="role-tags">
            <!-- 音色标签 -->
            <a-tag
              v-if="role.voiceId"
              size="small"
              color="purple"
              class="role-tag voice-tag"
            >
              <template #icon>
                <span class="voice-icon">🎵</span>
              </template>
              {{ getVoiceName(role.voiceId) }}
            </a-tag>
            
            <!-- 原有标签 -->
            <a-tag
              v-for="tag in (role.tags || []).slice(0, 2)"
              :key="tag"
              size="small"
              :color="getTagColor(tag)"
              class="role-tag"
            >
              {{ tag }}
            </a-tag>
            <span v-if="(role.tags || []).length > 2" class="more-tags">
              +{{ (role.tags || []).length - 2 }}
            </span>
          </div>
          
          <div class="role-meta">
            <span v-if="role.knowledgeId" class="knowledge-id"> {{ getKnowledgeName(role.knowledgeId) }}</span>
          </div>
        </div>
        
        <div class="role-actions">
          <a-button 
            type="text" 
            size="small" 
            @click.stop="handleEditRole(role)"
            :disabled="role.isDefault"
            :title="role.isDefault ? '默认角色不可编辑' : '编辑角色'"
          >
            <Edit2 :size="14" />
          </a-button>
          <a-button 
            type="text" 
            size="small" 
            @click.stop="handleDeleteRole(role)"
            :disabled="role.isDefault"
            :title="role.isDefault ? '默认角色不可删除' : '删除角色'"
          >
            <Trash2 :size="14" />
          </a-button>
        </div>
        
        <!-- 默认角色标识 -->
        <div v-if="role.isDefault" class="default-role-badge">
          <a-tag color="gold" size="small">
            <template #icon>
              <StarFilled />
            </template>
            默认角色
          </a-tag>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div v-if="roles.length > 0" class="pagination-container">
      <a-pagination
        v-model:current="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :show-size-changer="true"
        :show-quick-jumper="true"
        :show-total="(total: number, range: [number, number]) => {
          // 计算当前页实际显示的角色数量（包括默认角色）
          const currentPageStart = (pagination.current - 1) * pagination.pageSize + 1
          const currentPageEnd = Math.min(pagination.current * pagination.pageSize, total)
          const defaultRolesCount = roles.filter(role => role.isDefault).length
          const actualDisplayed = filteredRoles.length
          
          // 如果有默认角色，显示包含默认角色的总数
          if (defaultRolesCount > 0) {
            return `显示 ${actualDisplayed} 条角色（含 ${defaultRolesCount} 个默认角色），普通角色共 ${total} 条`
          } else {
            return `第 ${currentPageStart}-${currentPageEnd} 条，共 ${total} 条`
          }
        }"
        :page-size-options="['10', '20', '50']"
        @change="handlePageChange"
        @show-size-change="handlePageSizeChange"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="filteredRoles.length === 0 && !loading" class="empty-state">
      <div class="empty-icon">
        <Users :size="64" />
      </div>
      <h3>暂无角色</h3>
      <p>{{ searchKeyword || selectedTags.length > 0 ? '没有找到匹配的角色' : '还没有创建任何角色' }}</p>
      <a-button type="primary" @click="handleCreateRole">
        创建第一个角色
      </a-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" tip="加载中..." />
    </div>

    <!-- 弹窗组件 -->
    <RoleCreateModal
      v-model:open="createModalOpen"
      @success="handleCreateSuccess"
    />
    
    <RoleEditModal
      v-model:open="editModalOpen"
      :role="currentRole"
      @success="handleEditSuccess"
    />
    
    <RoleDeleteModal
      v-model:open="deleteModalOpen"
      :role="currentRole"
      @success="handleDeleteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Search, Edit2, Trash2, Users } from 'lucide-vue-next'
import { StarFilled } from '@ant-design/icons-vue'
import RoleCreateModal from '@/components/Role/RoleCreateModal.vue'
import RoleEditModal from '@/components/Role/RoleEditModal.vue'
import RoleDeleteModal from '@/components/Role/RoleDeleteModal.vue'
import CloneButton from '@/components/Voice/CloneButton.vue'
import roleService, { type ExtendedRole } from '@/api/roleService'
import { message } from 'ant-design-vue'
import type { KnowledgeBaseListVO } from '@/api/generated/data-contracts'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores/modules/auth'
import { useResourceStore } from '@/stores'

// 使用roleService中定义的ExtendedRole类型

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedTags = ref<string[]>([])

// 弹窗状态
const createModalOpen = ref(false)
const editModalOpen = ref(false)
const deleteModalOpen = ref(false)
const currentRole = ref<ExtendedRole | null>(null)



// 角色数据和分页信息
const roles = ref<ExtendedRole[]>([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 知识库数据
const knowledgeBases = ref<KnowledgeBaseListVO[]>([])
const authStore = useAuthStore()
const resourceStore = useResourceStore()



// 创建带认证头的API配置
const createAuthHeaders = () => {
  const token = authStore.token
  return token ? { Authorization: `Bearer ${token}` } : {}
}

// 加载知识库列表
const loadKnowledgeBases = async () => {
  try {
    const api = new Codewin({
      baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
    })
    const response = await api.getKnowledgeBaseList(
      {
        pageNo: 1,
        pageSize: 100
      },
      {
        headers: createAuthHeaders()
      }
    )
    
    if (response.data?.code === 0 && response.data.data?.list) {
      knowledgeBases.value = response.data.data.list
      console.log('知识库列表加载成功:', knowledgeBases.value)
    }
  } catch (error) {
    console.error('加载知识库列表失败:', error)
  }
}

// 加载角色列表（带重试机制）
const loadRoles = async (retryCount = 0) => {
  try {
    loading.value = true
    
    // 同时请求普通角色列表和默认角色列表
    const [normalResponse, defaultResponse] = await Promise.all([
      roleService.getRoleList({
        pageNo: pagination.value.current,
        pageSize: pagination.value.pageSize,
        keyword: searchKeyword.value,
        category: selectedCategory.value,
        tags: selectedTags.value
      }),
      roleService.getDefaultRoles({
        pageNo: 1, // 默认角色始终从第一页开始
        pageSize: 50 // 获取更多默认角色
      })
    ])
    
    console.log("加载普通角色列表成功:", normalResponse)
    console.log("加载默认角色列表成功:", defaultResponse)
    
    // 为默认角色添加标识字段
    const defaultRoles = defaultResponse.records.map(role => ({
      ...role,
      isDefault: true // 添加默认角色标识
    }))
    
    // 合并普通角色和默认角色，对相同ID进行去重，优先保留默认角色
    const roleMap = new Map()
    
    // 先添加普通角色
    normalResponse.records.forEach(role => {
      roleMap.set(role.id, role)
    })
    
    // 再添加默认角色，如果ID相同则覆盖普通角色
    defaultRoles.forEach(role => {
      roleMap.set(role.id, role)
    })
    
    // 转换为数组
    const allRoles = Array.from(roleMap.values())
    
    roles.value = allRoles
    // 分页信息以普通角色为准，因为默认角色不参与分页
    pagination.value.total = normalResponse.total
    pagination.value.current = normalResponse.current
    pagination.value.pageSize = normalResponse.size
  } catch (error) {
    console.error('加载角色列表失败:', error)
    
    // 网络错误时尝试重试（最多重试2次）
    if (retryCount < 2 && (error instanceof Error && error.message.includes('网络'))) {
      console.log(`重试加载角色列表，第${retryCount + 1}次重试`)
      setTimeout(() => loadRoles(retryCount + 1), 1000 * (retryCount + 1))
      return
    }
    
    if (error instanceof Error) {
      message.error(error.message)
    } else {
      message.error('加载角色列表失败，请重试')
    }
    // 加载失败时显示空状态
    roles.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 计算属性：过滤后的角色列表
const filteredRoles = computed(() => {
  // console.log(roles.value)
  let filtered = roles.value

  // 关键词搜索
  if (searchKeyword.value && typeof searchKeyword.value === 'string') {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(role =>
      (role.roleName || '').toLowerCase().includes(keyword) ||
      (role.prompt || '').toLowerCase().includes(keyword) ||
      (role.tags || []).some(tag => tag.toLowerCase().includes(keyword))
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(role => role.category === selectedCategory.value)
  }

  // 标签筛选
  if (selectedTags.value.length > 0) {
    filtered = filtered.filter(role =>
      selectedTags.value.every(tag => (role.tags || []).includes(tag))
    )
  }

  return filtered
})

// 方法
const handleSearch = (value: string) => {
  searchKeyword.value = value
  resetPaginationAndLoad()
}

const handleCategoryChange = (value: string) => {
  selectedCategory.value = value
  resetPaginationAndLoad()
}




const handleCreateRole = () => {
  createModalOpen.value = true
}

const handleRoleClick = (role: ExtendedRole) => {
  // TODO: 实现角色详情查看
  console.log('查看角色详情:', role)
}

const handleEditRole = (role: ExtendedRole) => {
  currentRole.value = role
  editModalOpen.value = true
}

const handleDeleteRole = (role: ExtendedRole) => {
  currentRole.value = role
  deleteModalOpen.value = true
}

// 弹窗事件处理
const handleCreateSuccess = async (newRole: ExtendedRole) => {
  try {
    await loadRoles() // 重新加载角色列表
    message.success('角色创建成功！')
  } catch (error) {
    // 创建成功但刷新列表失败
    message.warning('角色创建成功，但刷新列表失败，请手动刷新页面')
  }
}

const handleEditSuccess = async (updatedRole: ExtendedRole) => {
  try {
    await loadRoles() // 重新加载角色列表
    // message.success('角色更新成功！')
  } catch (error) {
    // 更新成功但刷新列表失败
    message.warning('角色更新成功，但刷新列表失败，请手动刷新页面')
  }
}

const handleDeleteSuccess = async (roleId: string) => {
  try {
    await loadRoles() // 重新加载角色列表
    // message.success('角色删除成功！')
  } catch (error) {
    // 删除成功但刷新列表失败
    message.warning('角色删除成功，但刷新列表失败，请手动刷新页面')
  }
}

// 音色克隆成功处理
const handleCloneSuccess = () => {
  message.success('音色克隆成功！')
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.value.current = page
  loadRoles()
}

const handlePageSizeChange = (current: number, size: number) => {
  pagination.value.current = 1
  pagination.value.pageSize = size
  loadRoles()
}

// 搜索和筛选时重置分页
const resetPaginationAndLoad = () => {
  pagination.value.current = 1
  loadRoles()
}

// 获取标签颜色
const getTagColor = (tag: string) => {
  const tagColors: Record<string, string> = {
    '默认': 'blue',
    '自定义': 'green',
    '推荐': 'orange',
    '热门': 'red',
    '经典': 'purple'
  }
  return tagColors[tag] || 'default'
}

// 获取知识库名称
const getKnowledgeName = (knowledgeId: string) => {
  // 首先在普通知识库中查找
  const knowledgeBase = knowledgeBases.value.find(kb => String(kb.id) === knowledgeId)
  if (knowledgeBase) {
    return knowledgeBase.name || `知识库-${knowledgeId}`
  }
  
  // 如果普通知识库中找不到，则使用resourceStore的allKnowledgeBasesMap查找（包含默认知识库）
  const allKnowledgeBase = resourceStore.allKnowledgeBasesMap.get(knowledgeId)
  return allKnowledgeBase?.name || `知识库-${knowledgeId}`
}

// 获取音色名称
const getVoiceName = (voiceId: string) => {
  return resourceStore.getVoiceName(voiceId)
}

onMounted(() => {
  // 初始化加载知识库列表和角色列表
  loadKnowledgeBases()
  loadRoles()
  // 初始化资源数据（音色和知识库）
  resourceStore.initResource()
})
</script>

<style scoped>
.role-page {
  padding: 24px;
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0;
  padding: 32px 32px 24px 32px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.8) 100%);
  border-radius: 16px 16px 0 0;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-bottom: none;
}

.header-content {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

.create-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  color: white !important;
  font-weight: 600 !important;
  height: 44px !important;
  padding: 0 24px !important;
  font-size: 14px !important;
}

.create-btn:hover {
  background: linear-gradient(135deg, #5b5bd6, #6a4c93) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4) !important;
}

.create-btn:active {
  transform: translateY(0) !important;
}

/* 搜索和筛选区域 */
.search-filter-section {
  margin-bottom: 24px;
  padding: 24px 32px 32px 32px;
  background: #f8f9fa;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.05);
  border: 1px solid #e9ecef;
  border-top: none;
}

.search-filter-row {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 0;
}

.search-container {
  flex: 1;
  position: relative;
}

.search-input {
  border-radius: 12px !important;
  border: 1px solid #e0e0e0 !important;
  transition: all 0.3s ease !important;
  background: white !important;
}

.search-input:focus,
.search-input:hover {
  border-color: #667eea !important;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2) !important;
}

.search-input:deep(.ant-input) {
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
  padding: 6px 8px !important;
  font-size: 16px !important;
}

.search-input:deep(.ant-input-prefix) {
  margin-right: 12px;
  color: #667eea;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-weight: 600;
  color: #374151;
  white-space: nowrap;
  font-size: 14px;
}

/* 角色卡片网格 */
.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .roles-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

.role-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
}

.role-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.role-card:hover::before {
  opacity: 1;
}

.role-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.role-info {
  flex: 1;
}

.role-name {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.3;
}

.role-description {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 63px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 16px;
  min-height: 24px;
}

.role-tag {
  border-radius: 6px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  border: none !important;
  transition: all 0.2s ease !important;
}

.voice-tag {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
}

.voice-icon {
  margin-right: 4px;
  font-size: 10px;
}

.more-tags {
  color: #999;
  font-size: 12px;
  font-weight: 500;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
}

.role-meta {
  margin-bottom: 16px;
  min-height: 20px;
}

.knowledge-id {
  color: #667eea;
  font-size: 12px;
  font-weight: 500;
  background: rgba(102, 126, 234, 0.1);
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
}

.role-actions {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.role-card:hover .role-actions {
  opacity: 1;
}

.role-actions .ant-btn {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.role-actions .ant-btn:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  transform: scale(1.1);
}

.role-actions .ant-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.role-actions .ant-btn:disabled:hover {
  background: rgba(255, 255, 255, 0.9);
  color: rgba(0, 0, 0, 0.25);
  transform: none;
}

.default-role-badge {
  position: absolute;
  top: 16px;
  left: 16px;
}

.default-role-badge .ant-tag {
  border-radius: 8px !important;
  font-weight: 600 !important;
  box-shadow: 0 2px 8px rgba(250, 173, 20, 0.3) !important;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 32px 0;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  color: #d9d9d9;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 18px;
  font-weight: 500;
}

.empty-state p {
  margin: 0 0 24px 0;
  color: #999;
  font-size: 14px;
}

.empty-state .ant-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 500;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 24px;
  }
  
  .search-filter-row {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .roles-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>